package com.atgm.mall.gmmailproduct.service.impl;

import com.atgm.common.constant.ProductConstant;
import com.atgm.common.exception.BizCodeEnume;
import com.atgm.common.exception.GameException;
import com.atgm.common.utils.GmMallUtils;
import com.atgm.mall.gmmailproduct.dao.*;
import com.atgm.mall.gmmailproduct.entity.*;
import com.atgm.mall.gmmailproduct.vo.AttrGroupRelationVo;
import com.atgm.mall.gmmailproduct.vo.resp.GameAttrVo;
import com.atgm.mall.gmmailproduct.vo.resp.GoodsAttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atgm.common.utils.PageUtils;
import com.atgm.common.utils.Query;

import com.atgm.mall.gmmailproduct.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private GameAttrRelaDao gameAttrRelaDao;

    @Autowired
    private GameAttrGroupRelaDao gameAttrGroupRelaDao;

    @Override
    @Cacheable(cacheNames = "game-attr", key = "#root.targetClass")
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageCond(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        if (GmMallUtils.isNotEmpty(key)) {
            queryWrapper.like("attr_name", key);
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    @CacheEvict(cacheNames = "game-attr", key = "#root.targetClass")
    public void saveAttr(AttrEntity attrEntity) {
        int count = baseMapper.insert(attrEntity);
        if (count != 1) {
            throw new GameException("添加游戏配置参数失败", BizCodeEnume.ATTR.getCode());
        }
    }


    @Override
    @CacheEvict(cacheNames = "game-attr", key = "#root.targetClass")
    public void updateAttr(AttrEntity attrEntity) {
        int count = baseMapper.updateById(attrEntity);
        if (count != 1) {
            throw new GameException("修改游戏配置参数失败", BizCodeEnume.ATTR.getCode());
        }
    }

    @Override
    @Transactional
    @CacheEvict(cacheNames = "game-attr", key = "#root.targetClass")
    public void deleteAttrById(Long id) {
        int count = baseMapper.deleteById(id);
        if (count != 1) {
            throw new GameException("删除游戏配置参数失败", BizCodeEnume.ATTR.getCode());
        }
        //删除关联信息
        QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_id", id);
        attrAttrgroupRelationDao.delete(queryWrapper);
    }

    /**
     * 获取属性分组的关联的所有属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        List<Long> attrIdList = entities.stream().map(attrAttrgroupRelationEntity -> {
            return attrAttrgroupRelationEntity.getAttrId();
        }).collect(Collectors.toList());

        if (GmMallUtils.isEmpty(attrIdList)) {
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(attrIdList);
        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        List<AttrAttrgroupRelationEntity> relationEntityList = Arrays.asList(vos).stream().map(vo -> {
            AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(vo, relation);
            return relation;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBatchRelation(relationEntityList);
    }

    /**
     * 获取属性分组没有关联的其他属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        //当前分类下所有分组

        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>();
        String key = (String) params.get("key");
        if (GmMallUtils.isNotEmpty(key)) {
            queryWrapper.and(wapper -> {
                wapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    @Override
    public List<GameAttrVo> queryGameGoodsAttrById(Long gameGoodsId) {
        //返回值
        List<GameAttrVo> gameAttrVos = new ArrayList<>();

        QueryWrapper<GameAttrGroupRelaEntity> gameAttrGroupRelaEntityQueryWrapper = new QueryWrapper<>();
        gameAttrGroupRelaEntityQueryWrapper.eq("game_id", gameGoodsId);
        List<GameAttrGroupRelaEntity> gameAttrGroupRelaEntities = gameAttrGroupRelaDao.selectList(gameAttrGroupRelaEntityQueryWrapper);
        if (GmMallUtils.isEmpty(gameAttrGroupRelaEntities)) {  //未绑定属性分组信息
            return null;
        }

        List<Long> attrGroupIds = gameAttrGroupRelaEntities.stream().map(GameAttrGroupRelaEntity::getAttrGroupId).collect(Collectors.toList());

        //获取属性分组信息
        QueryWrapper<AttrGroupEntity> attrGroupEntityQueryWrapper = new QueryWrapper<>();
        attrGroupEntityQueryWrapper.in("attr_group_id", attrGroupIds);
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(attrGroupEntityQueryWrapper);

        if (GmMallUtils.isNotEmpty(attrGroupEntities)) {
            attrGroupEntities.forEach(attrGroupEntity -> {
                GameAttrVo gameAttrVo = new GameAttrVo();
                gameAttrVo.setAttrGroupId(attrGroupEntity.getAttrGroupId());  //属性组id
                gameAttrVo.setAttrGroupName(attrGroupEntity.getAttrGroupName());  //属性组名称

                //获取属性组绑定的属性id
                QueryWrapper<AttrAttrgroupRelationEntity> attrGroupQueryWrapper = new QueryWrapper<>();
                attrGroupQueryWrapper.eq("attr_group_id", attrGroupEntity.getAttrGroupId());
                List<AttrAttrgroupRelationEntity> attrGroupRelaList = attrAttrgroupRelationDao.selectList(attrGroupQueryWrapper);
                List<Long> attrIdList = attrGroupRelaList.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

                //获取属性值信息
                QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<>();
                attrEntityQueryWrapper.select("attr_id", "attr_name");
                attrEntityQueryWrapper.in("attr_id", attrIdList);
                List<AttrEntity> attrList = attrDao.selectList(attrEntityQueryWrapper);

                //获取该游戏商品和属性的对应关系
                QueryWrapper<GameAttrRelaEntity> goodsAttrRelaEntityQueryWrapper = new QueryWrapper<>();
                goodsAttrRelaEntityQueryWrapper.eq("game_id", gameGoodsId);
                goodsAttrRelaEntityQueryWrapper.in("attr_id", attrIdList);
                goodsAttrRelaEntityQueryWrapper.in("attr_group_id", attrGroupEntity.getAttrGroupId());
                List<GameAttrRelaEntity> goodsAttrRelaList = gameAttrRelaDao.selectList(goodsAttrRelaEntityQueryWrapper);

                //商品、属性值
                List<GoodsAttrVo> goodsAttrVos = new ArrayList<>();
                attrList.forEach(attrEntity -> {
                    GoodsAttrVo goodsAttrVo = new GoodsAttrVo();
                    goodsAttrVo.setAttrId(attrEntity.getAttrId());
                    goodsAttrVo.setAttrName(attrEntity.getAttrName());
                    goodsAttrVo.setGoodsId(gameGoodsId);
                    goodsAttrVo.setValue(goodsAttrRelaList.stream().filter(goodsAttrRelaEntity ->
                            goodsAttrRelaEntity.getAttrId().equals(attrEntity.getAttrId())).findAny().get().getValue());
                    goodsAttrVos.add(goodsAttrVo);
                });

                gameAttrVo.setAttrList(goodsAttrVos);
                gameAttrVos.add(gameAttrVo);
            });
        }

        return gameAttrVos;
    }
}